package com.adb.receivecontent.utility;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.util.Log;

import com.adb.receivecontent.bean.LinkMagnetBean;
import com.adb.receivecontent.bean.LinkParam;

public class NewHttpFileUpload {
	
	 URL connectURL;
	 HttpURLConnection conn = null;
	 DataOutputStream dos = null;
     String responseString;
     String Title;
     String Description;
     byte[ ] dataToServer;
     FileInputStream fileInputStream = null;
     int bytesRead, bytesAvailable, bufferSize;
     byte[] buffer;
     int maxBufferSize = 1 * 1024;
     public NewHttpFileUpload() {
	}
     
	public String postImageIMEI(Context mContext, String vLocalPath,
			LinkMagnetBean vBeanApdater) {
		String strResult = "";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String Tag = "fSnd";
		try {
			
			
			Log.e(Tag, "Starting Http File Sending to URL");
			
			fileInputStream = new FileInputStream(vLocalPath);
			connectURL = new URL(vBeanApdater.getStrlinkurl());	// URL 
	        Title= vBeanApdater.getStrlinkName();	// link name
	        Description = vBeanApdater.getStrlinkName(); // link name

			// Open a HTTP connection to the URL
			conn = (HttpURLConnection) connectURL.openConnection();
					

			// Allow Inputs
			conn.setDoInput(true);

			// Allow Outputs
			conn.setDoOutput(true);

			// Don't use a cached copy.
			conn.setUseCaches(false);
			
			conn.setChunkedStreamingMode(1024);
			
			// Use a post method.
			conn.setRequestMethod("POST");
			
			conn.setRequestProperty("Connection", "Keep-Alive");

			conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
			
			for(int i =0 ;i<vBeanApdater.getmArrayListParams().size();i++){
				LinkParam mTempParam = vBeanApdater.getmArrayListParams().get(i);
				conn.setRequestProperty(mTempParam.getStrKey(), mTempParam.getStrValue());	
			}
			
			
			dos = new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+vBeanApdater.getStrFileName().trim()+"\";filename=\"" +vLocalPath+"\"" + lineEnd);
			dos.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available();
	        bufferSize = Math.min(bytesAvailable, maxBufferSize);
	        buffer = new byte[bufferSize];
 
	        // Read file
	        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	        System.out.println("Image length " + bytesAvailable + "");
	        try {
	            while (bytesRead > 0) {
	                try {
	                    dos.write(buffer, 0, bufferSize);
	                } catch (OutOfMemoryError e) {
	                    e.printStackTrace();
	                  
	                }
	                bytesAvailable = fileInputStream.available();
	                bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			int serverResponseCode = conn.getResponseCode();
		    String serverResponseMessage = conn.getResponseMessage();
	        System.out.println("Server Response Code " + " " + serverResponseCode);
	        System.out.println("Server Response Message "+ serverResponseMessage);
		        
			InputStream is = conn.getInputStream();

			strResult = convertStreamToString(is);
			
			// close streams
			fileInputStream.close();
			dos.flush();
			dos.close();
			conn.disconnect();
			
			
		} catch (Exception ex) {
			Log.e(Tag, "URL error: " + ex.getMessage(), ex);
		
		}finally{
			
			if(conn != null){
				
				try {
					
					dos.flush();
					dos.close();
					conn.disconnect();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}
			
			
		}
		return strResult;
	}

	private String convertStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		try {
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (Exception e) {

		}
		return total.toString();
	}
}
